<template>

  <div class="app-container">

    <div class="tabs" style="width: 100%">

      <!-- 项目列表树组件 -->
      <projectTreeView
        ref="projectTree"
        class="projectTree"
        :busEventNameOneClick="$busEvents.projectTreeChoiceProject"
        :busEventNameTwoClick="$busEvents.taskDialogIsShow"
      ></projectTreeView>

      <!-- 测试报告列表 -->
      <el-tabs v-model="reportTab" class="table_padding reportTab">

        <!-- 用例管理 -->
        <el-tab-pane label="测试报告列表" :name="reportTab">

          <!-- 根据当前窗口宽度，实时计算用例列表能展示的宽度 -->
          <el-row :style="{'min-width': reportListTableWidth}">

            <el-col :span="21" style="padding-left: 5px;">
              <el-table
                ref="reportTable"
                :data="reportDataList"
                @row-dblclick="doubleClick"
                stripe
              >

                <el-table-column
                  prop="id"
                  label="id"
                  min-width="8%">
                </el-table-column>

                <el-table-column :show-overflow-tooltip=true prop="name" label="任务名称" min-width="25%">
                  <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" content="双击查看详情" placement="right-end">
                      <span> {{ scope.row.name }} </span>
                    </el-tooltip>

                  </template>
                </el-table-column>

                <el-table-column label="生成时间" min-width="17%">
                  <template slot-scope="scope">
                    <span> {{ scope.row.created_time }} </span>
                  </template>
                </el-table-column>

                <el-table-column
                  prop="performer"
                  label="创建者"
                  min-width="8%">
                </el-table-column>

                <el-table-column label="是否通过" min-width="10%">
                  <template slot-scope="scope">
                    <el-tag size="small" :type="scope.row.is_passed === 1 ? 'success' : 'danger'">
                      {{ scope.row.is_passed === 1 ? '全部通过' : '有报错' }}
                    </el-tag>
                  </template>
                </el-table-column>

                <el-table-column label="状态" min-width="8%">
                  <template slot-scope="scope">
                    <el-tag size="small" :type="scope.row.status === '已读' ? 'success' : 'warning'">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>

                <el-table-column label="操作" min-width="22%">
                  <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click.native="downReport(scope.row.id)">下载</el-button>
                    <el-button type="danger"
                               size="mini"
                               @click.native="confirmBox(delReport, scope.row.id, scope.row.name)">删除
                    </el-button>
                  </template>
                </el-table-column>


              </el-table>

              <pagination
                v-show="reportTotal>0"
                :total="reportTotal"
                :page.sync="PageNum"
                :limit.sync="PageSize"
                @pagination="getReportList"
              />
            </el-col>
          </el-row>
        </el-tab-pane>

      </el-tabs>

    </div>

  </div>
</template>

<script>

import projectTreeView from '@/components/Trees/projectTree'
import Pagination from '@/components/Pagination'

import {reportList, deleteReport, downloadReport, getReport} from '@/apis/report'

export default {
  name: 'index',
  components: {Pagination, projectTreeView},
  data() {
    return {
      reportTab: 'reportTab',
      projectId: '',
      reportDataList: [],
      reportTotal: 0,
      PageNum: 0,
      PageSize: 20,
    }
  },
  methods: {

    // 双击查看测试报告
    doubleClick(row, column, event) {
      let {href} = this.$router.resolve({path: 'reportShow', query: {id: row.id}})
      window.open(href, '_blank')
    },

    // 获取项目对应的报告列表
    getReportList() {
      reportList({projectId: this.projectId, pageNum: this.PageNum, pageSize: this.PageSize}).then(response => {
        this.reportDataList = response.data.data
        this.reportTotal = response.data.total
      })
    },

    // 打开测试报告
    // openReportById(reportId) {
    //   console.log(`api.dialogForm.openReportById.reportId: ${JSON.stringify(reportId)}`)
    //   let {href} = this.$router.resolve({path: 'reportShow', query: {id: reportId}})
    //   window.open(href, '_blank')
    // },

    // 下载测试报告按钮
    downReport(reportId) {
      downloadReport({'id': reportId}).then((response) => {
          this.renderHtml(response.data, "测试报告.html", "text/html")
        }
      )
    },

    // 把数据转为html
    renderHtml(data, strFileName, strMimeType) {

      let self = window, // this script is only for browsers anyway...
        defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
        mimeType = strMimeType || defaultMime,
        payload = data,
        anchor = document.createElement("a"),
        toString = function (a) {
          return String(a);
        },
        myBlob = (self.Blob || self.MozBlob || self.WebKitBlob || toString),
        fileName = strFileName || "download",
        blob,
        reader;
      myBlob = myBlob.call ? myBlob.bind(self) : Blob;

      //go ahead and download dataURLs right away
      blob = payload instanceof myBlob ?
        payload :
        new myBlob([payload], {type: mimeType});


      function saver(url, winMode) {
        if ('download' in anchor) { //html5 A[download]
          anchor.href = url;
          anchor.setAttribute("download", fileName);
          anchor.className = "download-js-link";
          anchor.innerHTML = "downloading...";
          anchor.style.display = "none";
          document.body.appendChild(anchor);
          setTimeout(function () {
            anchor.click();
            document.body.removeChild(anchor);
            if (winMode === true) {
              setTimeout(function () {
                self.URL.revokeObjectURL(anchor.href);
              }, 250);
            }
          }, 66);
          return true;
        }

      }//end saver

      if (self.URL) { // simple fast and modern way using Blob and URL:
        saver(self.URL.createObjectURL(blob), true);
      } else {
        // handle non-Blob()+non-URL browsers:
        if (typeof blob === "string" || blob.constructor === toString) {
          try {
            return saver("data:" + mimeType + ";base64," + self.btoa(blob));
          } catch (y) {
            return saver("data:" + mimeType + "," + encodeURIComponent(blob));
          }
        }

        // Blob but not URL support:
        reader = new FileReader();
        reader.onload = function () {
          saver(this.result);
        };
        reader.readAsDataURL(blob);
      }
      return true;
    },

    // 删除报告
    delReport(reportId) {
      deleteReport({id: reportId}).then(response => {
        if (this.showMessage(this, response)) {
          this.getReportList()
        }
      })
    },
  },

  mounted() {
    this.$bus.$on(this.$busEvents.projectTreeChoiceProject, (project) => {
      this.projectId = project.id
      this.getReportList()
    })
  },

  // 页面销毁前，关闭bus监听项目选中事件
  beforeDestroy() {
    this.$bus.$off(this.$busEvents.projectTreeChoiceProject)
  },

  computed: {
    // 用例列表能用的宽度
    reportListTableWidth() {
      return `${window.innerWidth - 700}px`
    }
  },
}
</script>

<style scoped>
.projectTree {
  float: left;
  width: 200px;
}
</style>
